import userInfoApi from '../../../services/user/userInfo';

import {
  upload
} from '../../../services/_utils/request';

Page({
  data: {
    personInfo: null,
    isChoosedImg: false,
    imgPath: null
  },
  onLoad() {
    let globalInfo = getApp().globalData.userInfo
    this.setData({
      personInfo: {
        avatarUrl: globalInfo.avatarUrl,
        userName: globalInfo.userName,
        userId: globalInfo.userId
      }
    })
  },
  openUnbindConfirm() {
    wx.showLoading({
      title: '处理中',
    })
    var that = this
    if (!that.data.isChoosedImg) {
      console.log(that.data.personInfo)
      userInfoApi.edit(that.data.personInfo).then(res => {
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 1500,
          success: function () {
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              });
            }, 1500);
          }
        })
      });
    } else {
      that.uploadImg(that.data.imgPath).then(res => {
        console.log(that.data.personInfo)
        userInfoApi.edit(that.data.personInfo).then(res => {
          wx.showToast({
            title: '成功',
            icon: 'success',
            duration: 2000
          })
        });
      })
    }
  },

  bindTextAreaInput: function (e) {
    console.log(e.detail.value)
    this.setData({
      ['personInfo.userName']: e.detail.value
    });
  },

  uploadImg(path) {
    var that = this
    return new Promise((resolve, reject) => {
      upload(path).then(data => {
        console.log("upload", data)
        that.setData({
          ['personInfo.avatarUrl']: data
        });
        resolve();
      })
    });
  },
  chooseImg: function (e) {
    var that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log(res.tempFiles[0].tempFilePath)
        that.setData({
          ['personInfo.avatarUrl']: res.tempFiles[0].tempFilePath,
          imgPath: res.tempFiles[0].tempFilePath,
          isChoosedImg: true
        })
      }
    })
  },
});